package com.heer.gymnasium.fragment;

import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.bigkoo.svprogresshud.SVProgressHUD;
import com.heer.api.ResponseData.ApiResponse;
import com.heer.api.callback.BaseCallback;
import com.heer.gymnasium.R;
import com.heer.gymnasium.adapter.OrderAllAdapter;
import com.heer.gymnasium.adapter.OrderFilterAdapter;
import com.heer.gymnasium.constant.Type;
import com.heer.gymnasium.event.BaseEvent;
import com.heer.model.OrderBean;
import com.heer.model.OrderFilterBean;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import retrofit2.Call;
import retrofit2.Response;

import static com.heer.gymnasium.event.EventConstant.CANCEL_ORDER;
import static com.heer.gymnasium.event.EventConstant.CREATE_ORDER;

/**
 * Created by heer on 17/4/9.
 */

public class OrderAllFragment extends BaseRefreshFragment {
    @BindView(R.id.list)
    ListView list;
    @BindView(R.id.edit)
    EditText edit;
    @BindView(R.id.layout_edit)
    LinearLayout layoutEdit;
    @BindView(R.id.layout_content)
    LinearLayout layoutContent;
    @BindView(R.id.layout_refresh)
    SwipyRefreshLayout layoutRefresh;

    private static final String EXTRA_DATA = "type";
    private SVProgressHUD svProgressHUD;

    private OrderAllAdapter mAdapter;
    private OrderFilterAdapter mFilterAdapter;
    private int type;
    private int ptype;
    private boolean loadMore;
    private List<OrderFilterBean> filterList;
    private PopupWindow filterPop;
    private boolean firstLoaded = false;


    public static OrderAllFragment newInstance(int type) {
        OrderAllFragment array = new OrderAllFragment();
        Bundle args = new Bundle();
        args.putInt(EXTRA_DATA, type);
        array.setArguments(args);
        return array;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        type = getArguments() != null ? getArguments().getInt(EXTRA_DATA) : Type.ORDER_ALL;
        Log.e("typevaluebegin", type + "");
        ptype = type;
    }

    @Override
    protected void bindView(View view) {
        super.bindView(addContentView(view, R.layout.fragment_order_all));
    }

    @Override
    protected void init() {
        super.init();
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
    }

    @Override
    protected void initView() {
        super.initView();
        if (type != Type.ORDER_ALL) {
            layoutEdit.setVisibility(View.GONE);
        } else {
            layoutEdit.setVisibility(View.VISIBLE);

            LayoutInflater inflater = LayoutInflater.from(mContext);
            // 引入窗口配置文件
            View view = inflater.inflate(R.layout.layout_order_filter, null);
            // 创建PopupWindow对象
            filterPop = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, false);
            ListView lv = (ListView) view.findViewById(R.id.list);
            lv.setAdapter(mFilterAdapter = new OrderFilterAdapter(mContext));
            // 需要设置一下此参数，点击外边可消失
            filterPop.setBackgroundDrawable(new BitmapDrawable());
            //设置点击窗口外边窗口消失
            filterPop.setOutsideTouchable(true);
            // 设置此参数获得焦点，否则无法点击
            filterPop.setFocusable(true);

            filterList = new ArrayList<>();
            for (int i = 0; i < 5; i++) {
                OrderFilterBean item = null;
                switch (i) {
                    case 0:
                        item = new OrderFilterBean("全部", String.valueOf(Type.ORDER_ALL), true);
                        break;
                    case 1:
                        item = new OrderFilterBean("未支付", String.valueOf(Type.ORDER_UNPAID), false);
                        break;
                    case 2:
                        item = new OrderFilterBean("支付成功", String.valueOf(Type.ORDER_PAID_SUCCESS), false);
                        break;
                    case 3:
                        item = new OrderFilterBean("未使用", String.valueOf(Type.ORDER_USABLE), false);
                        break;
                    case 4:
                        item = new OrderFilterBean("已使用", String.valueOf(Type.ORDER_USED), false);
                        break;
                }
                filterList.add(item);
            }
            mFilterAdapter.setItems(filterList);

            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    ptype = Integer.valueOf(filterList.get(position).getType());
                    edit.setText(filterList.get(position).getName());
                    for (OrderFilterBean item : filterList) {
                        if (Integer.valueOf(item.getType()) == ptype) {
                            item.setSelect(true);
                        } else {
                            item.setSelect(false);
                        }
                    }
                    reqData(false);
                    mFilterAdapter.notifyDataSetChanged();

                    if (filterPop.isShowing()) {
                        filterPop.dismiss();
                    }
                }
            });

            edit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (filterPop.isShowing()) {
                        // 隐藏窗口，如果设置了点击窗口外小时即不需要此方式隐藏
                        filterPop.dismiss();
                    } else {
                        // 显示窗口
                        filterPop.showAsDropDown(v);
                    }
                }
            });
        }
        list.setAdapter(mAdapter = new OrderAllAdapter(getActivity(), type));
        layoutContent.setVisibility(View.GONE);
        layoutRefresh.setOnRefreshListener(this);
        btnRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                reqData(false);
            }
        });
    }

    public void initFirst(){
        if(!firstLoaded)
        {

            ptype=1;
            reqData(false);
        }
    }

    public void reqData(boolean loadmore){
        svProgressHUD.showWithStatus("加载中", SVProgressHUD.SVProgressHUDMaskType.BlackCancel);
        loadMore = loadmore;
        Log.e("typevalue", ptype + "");
        switch (ptype) {
            case Type.ORDER_ALL:
                mAppHelper.apiService().getOrderList(
                        null,
                        "21",
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        String.valueOf(pageNo)
                ).enqueue(callback);
                break;
            case Type.ORDER_USABLE:
                mAppHelper.apiService().getOrderList(
                        null,
                        "21",
                        null,
                        null,
                        null,
                        null,
                        "1",
                        "1",
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        String.valueOf(pageNo)
                ).enqueue(callback);
                break;
            case Type.ORDER_UNPAID:
                mAppHelper.apiService().getOrderList(
                        null,
                        "21",
                        null,
                        null,
                        null,
                        null,
                        "0",
                        "1",
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        String.valueOf(pageNo)
                ).enqueue(callback);
                break;
            case Type.ORDER_PAID_SUCCESS:
                mAppHelper.apiService().getOrderList(
                        null,
                        "21",
                        null,
                        null,
                        null,
                        null,
                        "1",
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        String.valueOf(pageNo)
                ).enqueue(callback);
                break;
            case Type.ORDER_USED:
                mAppHelper.apiService().getOrderList(
                        null,
                        "21",
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        "1",
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        String.valueOf(pageNo)
                ).enqueue(callback);
                break;
        }
    }

    @Override
    protected void loadData(boolean loadmore) {
        super.loadData(loadmore);
        if(loadmore)
            reqData(loadmore);
        else if (firstLoaded)
            reqData(loadmore);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void eventBus(BaseEvent event) {
        if (TextUtils.equals(event.getId(), CANCEL_ORDER) || TextUtils.equals(event.getId(), CREATE_ORDER)) {
            ptype=1;
            reqData(false);
        }
    }

    BaseCallback<ApiResponse<List<OrderBean>>> callback = new BaseCallback<ApiResponse<List<OrderBean>>>() {
        @Override
        public void onResponse(Call<ApiResponse<List<OrderBean>>> call, Response<ApiResponse<List<OrderBean>>> response) {
            super.onResponse(call, response);
            firstLoaded=true;
            layoutRefresh.setRefreshing(false);
            svProgressHUD.dismiss();
            if (response.isSuccessful() && response.body().isSccessful()) {
                if (loadMore) {
                    mAdapter.addItems(response.body().getData());
                } else {
                    mAdapter.clearItems();
                    mAdapter.setItems(response.body().getData());
                }

                if (mAdapter.getItemList().size() > 0) {
                    if (layoutContent.getVisibility() == View.GONE)
                        layoutContent.setVisibility(View.VISIBLE);
                    if (layoutNoData.getVisibility() == View.VISIBLE)
                        layoutNoData.setVisibility(View.GONE);
                } else {
                    if (layoutNoData.getVisibility() == View.GONE)
                        layoutNoData.setVisibility(View.VISIBLE);
                }
            }
            if (response.isSuccessful() && response.body().isTokenExpire()) {
                toLogin();
            }
        }

        @Override
        public void onFailure(Call<ApiResponse<List<OrderBean>>> call, Throwable t) {
            super.onFailure(call, t);
            layoutRefresh.setRefreshing(false);
            svProgressHUD.dismiss();
        }
    };

    public void setSvProgressHUD(SVProgressHUD svProgressHUD) {
        this.svProgressHUD = svProgressHUD;
    }
}